package tx.bj12320.service;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import tx.bj12320.model.UserInfo;






@Service
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {
	protected Log log = LogFactory.getLog(getClass());
	@Autowired
	private UserInfoManager userInfoManager;
	public void setUserInfoManager(UserInfoManager manager) {
		this.userInfoManager = manager;
	}

	/**
	 * 获取用户Details信息的回调函数.
	 */
	@Transactional(readOnly=true)
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		String loginUserName="";
		String loginPassword="";
		UserInfo ui=userInfoManager.getByUsername(userName);
//		log.info(ui.getRealName());
//		System.out.println(ui.getRealName());
			if(ui!=null){
				loginUserName=ui.getUserName();
				loginPassword=ui.getPassword();
				authSet.add(new GrantedAuthorityImpl(ui.getSysUserType()));
			}else{
				throw new UsernameNotFoundException("用户" + userName + " 不存在");
			}

		User userdetail = new User(
				loginUserName, loginPassword, enabled, accountNonExpired, credentialsNonExpired,
				accountNonLocked, authSet);

		return userdetail;
	}


}
